package com.zl.gmadmin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zl.gmadmin.payload.WorkflowQueryCriteria;
import com.zl.gmadmin.service.WorkflowService;
import com.zl.gmadmin.utils.*;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ZhangLiang
 * @Date: 2021/09/04/11:41
 * @Description:
 */
@Service
public class WorkflowServiceImpl implements WorkflowService {


    private final RepositoryService repositoryService;

    public WorkflowServiceImpl(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }


    @Override
    public Optional<Object> selectPageVo(WorkflowQueryCriteria queryCriteria, Page page) {

        //1.创建ProcessEngine
//        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//
//        //2.repositoryService
//        RepositoryService repositoryService = processEngine.getRepositoryService();

        //3.得到ProcessDefinitionQuery对象,克认为即使一个查询器
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();

        LogUtil.debug("分页: "+JsonUtil.toJsonStr(page));
        //4.设置条件，查询出当前所有流程定义,流程定义的key=holiday
        List<ProcessDefinition> list = processDefinitionQuery.listPage((int)page.getTotal(),(int)page.getSize());
//                processDefinitionQuery.listPage((int)page.getCurrent(),(int)page.getSize());
        System.out.println("我没有问题了: " + list.size());
        //5.输出流程定义信息
        for (ProcessDefinition processDefinition : list) {

            System.out.println("id" + processDefinition.getId());
            System.out.println("key" + processDefinition.getKey());
            System.out.println("版本" + processDefinition.getVersion());
            System.out.println("名称" + processDefinition.getName());
        }

//        org.activiti.api.runtime.shared.query.Page<ProcessInstance>  processInstancePage =
//                processRuntime.processInstances(Pageable.of(0, 100));
//        System.out.println(processInstancePage.getTotalItems());
//        List<ProcessInstance> list=processInstancePage.getContent();
//
//        for (ProcessInstance p: list
//             ) {
//            System.out.println(p.getId());
//        }

        List<Map<String, Object>> mapList = ObjectsUtils.activitiResult(list);
        return Optional.of(PageUtils.toPage(mapList, processDefinitionQuery.count()));
    }

    @Override
    public void getProcessResources(String deploymentId, String resourceName, HttpServletResponse response) {

        InputStream inputStream = repositoryService.getResourceAsStream(deploymentId, resourceName);
        try {
            int count = inputStream.available();
            byte[] bytes = new byte[count];
            response.setContentType("text/xml");
            OutputStream outputStream = response.getOutputStream();
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addBPMNAndDeployment(WorkflowQueryCriteria addXMLRequest) {
        System.out.println(addXMLRequest.getSvg());
        LogUtil.debug("新增：  " + JsonUtil.toJsonStr(addXMLRequest));
        // svg转png输入流
        File file=null;
        FileInputStream fileInputStream=null;
        try {
            ImageUtils.convertToPng(addXMLRequest.getSvg(),  addXMLRequest.getName() + ".png");
             file = new File(addXMLRequest.getName() + ".png");
             fileInputStream=new FileInputStream(file);
            repositoryService.createDeployment()
                    .addString(addXMLRequest.getName() + ".bpmn", addXMLRequest.getXml())
                    .addInputStream(addXMLRequest.getName() + ".png", fileInputStream)
                    .name(addXMLRequest.getName())
                    .deploy();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TranscoderException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
                if (file.exists()){
                    file.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void delBPMNAndDeployment(List<String> ids) {
        ids.forEach(id -> {
            repositoryService.deleteDeployment(id);
        });
    }

    @Override
    public void updateBPMNAndDeployment() {

    }
}
